<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>审核表单</span>
        </div>
      </template>
      <div class="page-content">
        <component
          ref="componentRef"
          :is="component"
          :id="formId"
          :submitForm="submitForm"
          :disabled="disabled"
          :isFlow="true"
          class="form-container" />
        <!-- 修订 -->
        <Annotation
          ref="annotationRef"
          :annotationList="oldFormData?.formFieldRevisionLogs?.filter(item => item.hide === '1') || []"
          :workFlowId="workFlowId"
          :componentRef="componentRef?.formData"
          :oldFormData="oldFormData" />
      </div>
    </el-card>
    <el-card v-if="!disabled && route?.query?.type !== 'refresh'" style="margin-top: 20px">
      <template #header>
        <div class="card-header">审核</div>
      </template>
      <el-form
        v-if="route?.query?.type !== 'refresh'"
        label-width="80px"
        ref="formRef"
        :model="formData"
        :rules="rules"
        class="demo-form-inline">
        <el-form-item label="审核意见" prop="opinion">
          <el-input type="textarea" v-model="formData.opinion" placeholder="请输入审核意见" :rows="4" />
        </el-form-item>
      </el-form>
    </el-card>
    <div class="form-footer">
      <el-button v-if="isAginst" type="primary" @click="handleSubmitReview('1')">重新提交</el-button>
      <!-- v-if="!isAginst && route?.query?.type !== 'view'" -->
      <el-button type="primary" @click="handleSubmitReview('1')">
        {{ workFlowId === '15' ? '确认' : '通过' }}
      </el-button>
      <el-button
        v-if="!isAginst && route?.query?.type !== 'view' && workFlowId !== '15'"
        type="warning"
        @click="handleTransfer">
        转办
      </el-button>
      <el-button
        v-if="!isAginst && route?.query?.type !== 'view' && workFlowId === '5'"
        type="danger"
        @click="handleReturn('3')">
        不予立案
      </el-button>
      <el-button v-if="!isAginst && route?.query?.type !== 'view'" type="danger" @click="handleReturn('2')">
        退回
      </el-button>
      <el-button @click="handleFlowRecord">流转记录</el-button>
      <el-button @click="router.back()">返回</el-button>
    </div>
    <UserSelect
      ref="userSelectRef"
      v-model="userDialog"
      :taskId="String(route?.query?.taskId || '')"
      @submit="handleSubmitTransfer" />
    <flow-record v-model:modelValue="circulationVisible" :flow-list="circulationList" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, shallowRef, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import penaltyDetail from '@/views/workbench/penalty/delayApproval/detail.vue'
import UserSelect from '@/components/userSelect/index.vue'
import { ElMessage } from 'element-plus'
import flowRecord from '@/components/flowRecord/index.vue'
import { getTodoFlowRecord } from '@/api/workFlow/index'
import Annotation from '../annotation.vue'
import ReminderLetterDetail from '@/views/workbench/penalty/reminderLetterApp/detail.vue'
import CompulsoryAppDetail from '@/views/workbench/penalty/compulsoryApp/detail.vue'
import CaseClosedDetail from '@/views/workbench/caseClosed/detail.vue'
import RegisterDetail from '@/views/workbench/filingReview/register/detail.vue'
import PriorNoticeDetail from '@/views/workbench/priorNotice/approval/detail.vue'
import CaseHandlingApprovalDetail from '@/views/workbench/caseHandling/approval/detail.vue'
import LegalReviewDetail from '@/views/workbench/caseHandling/legalReview/detail.vue'
import CaseWithdrawalDetail from '@/views/workbench/caseWithdrawal/detail.vue'
import HearingNoticeDetail from '@/views/workbench/hearingNotice/approval/detail.vue'
import ApplicationDetail from '@/views/workbench/hearingNotice/application/detail.vue'

import { todoItemTransfer } from '@/api/penalty/delayApproval'
import { transferCompulsoryitemapproval } from '@/api/compulsoryApp/index'
import { transferNoticedemandapproval } from '@/api/reminderLetterApp/index'
import { transferCaseclosureapproval } from '@/api/caseClosed/index'
import { transferRegistrationcase } from '@/api/filingReview/register'
import { transferPenaltyAdvanceNotice } from '@/api/priorNotice/approval'
import { transferCaseProcessApproval } from '@/api/caseHandling/approval'
import { transferLegalReviewOpinion } from '@/api/caseHandling/legalReview'
import { transferCasecancelapproval } from '@/api/caseWithdrawal/index'
import { transferHearingNoticeApproval } from '@/api/hearingNotice/approval'
import { transferHearingRequest } from '@/api/hearingNotice/application'

const { proxy } = getCurrentInstance()

const router = useRouter()
const route = useRoute()
const disabled = route?.query?.type === 'view' // 是否禁用审核表单
const workFlowId = ref<any>('1')
const formId = ref<any>('')
const component = shallowRef<any>(null)

const formRef = ref<any>(null)
const formData = ref<any>({
  opinion: '',
})
const rules = {
  opinion: [{ required: true, message: '请输入审核意见', trigger: ['blur', 'change'] }],
}

const submitForm = ref<any>({})
const componentRef = ref<any>(null)
const annotationRef = ref<any>(null)
// 是否是重新提交
const isAginst = computed(() => route?.query?.type === 'refresh' && oldFormData.value?.applyStatus === '2')
// 通过 / 重新提交
const handleSubmitReview = (status: string) => {
  if (route?.query?.type === 'refresh') {
    formData.value.opinion = '同意'
    handleSubmit(status)
  } else {
    let VaidList = []
    if (workFlowId.value === '5') {
      // 立案审批表
      VaidList = [formRef.value.validate(), componentRef.value?.formValidate()]
    } else {
      console.log('componentRef.value?.formRef', componentRef.value.formRef.validate)
      VaidList = [formRef.value.validate(), componentRef.value.formRef.validate()]
    }
    Promise.all(VaidList)
      .then(valid => {
        if (valid[0] && valid[1]) {
          handleSubmit(status)
        }
      })
      .catch(err => {
        console.error('表单验证失败', err)
        ElMessage.warning('请完善表单信息') // 验证失败，提示用户
      })
  }
}

// 退回 / 不予立案
const handleReturn = (status: string) => {
  formRef.value?.validate(valid => {
    if (valid) {
      proxy.$modal
        .confirm(`是否确认${status === '2' ? '退回' : '不予立案'}当前任务？`)
        .then(function () {
          handleSubmit(status)
        })
        .catch(() => {})
    }
  })
}

async function handleSubmit(status) {
  submitForm.value = {
    action: status,
    taskId: route?.query?.taskId,
    opinion: formData.value.opinion,
  }
  nextTick(async () => {
    console.log('新表单', componentRef.value?.formData)
    const changes = await annotationRef.value.checkChange()

    if (changes.length > 0) {
      console.log('检测到以下字段变更:', changes)
      // // 可以在这里添加确认对话框或其他逻辑
      // ElMessage.info(`检测到 ${changes.length} 个字段发生变更`)
    } else {
      console.log('未检测到表单数据变更')
    }

    // 将变更信息添加到提交数据中
    submitForm.value.formFieldRevisionLogs = changes

    componentRef.value?.handleSubmitReview(submitForm.value)
  })
}

// 转办
/** 转办按钮操作 */
const userDialog = ref(false)
function handleTransfer() {
  userDialog.value = true
}
const handleSubmitTransfer = async (params: any) => {
  let transferApi: any = null
  if (workFlowId.value === '1') {
    // 延期缴纳罚款审批单
    transferApi = todoItemTransfer
  } else if (workFlowId.value === '2') {
    // 行政强制措施事项审批表
    transferApi = transferCompulsoryitemapproval
  } else if (workFlowId.value === '3') {
    // 催告书审批表
    transferApi = transferNoticedemandapproval
  } else if (workFlowId.value === '4') {
    // 结案
    transferApi = transferCaseclosureapproval
  } else if (workFlowId.value === '5') {
    // 立案审批表
    transferApi = transferRegistrationcase
  } else if (workFlowId.value === '6') {
    // 事先告知审批表
    transferApi = transferPenaltyAdvanceNotice
  } else if (['7', '8'].includes(workFlowId.value)) {
    // 案件处理审批表
    transferApi = transferCaseProcessApproval
  } else if (workFlowId.value === '9') {
    // 法制审核意见书
    transferApi = transferLegalReviewOpinion
  } else if (workFlowId.value === '10') {
    // 撤案审批
    transferApi = transferCasecancelapproval
  } else if (workFlowId.value === '11') {
    // 听证告知审批表
    transferApi = transferHearingNoticeApproval
  } else if (workFlowId.value === '15') {
    // 听证申请审批表
    transferApi = transferHearingRequest
  } else {
    ElMessage.warning('该流程暂不支持转办')
    return
  }
  await transferApi(params)
  userDialog.value = false
  ElMessage.success('转办成功')
  router.back()
}

const circulationList = ref([])
const circulationVisible = ref(false)
/** 流转记录按钮操作 */
async function handleFlowRecord() {
  const res = await getTodoFlowRecord({ instanceId: route.query?.instanceId, order: '1' })
  const { data } = res
  circulationList.value = data
  circulationVisible.value = true
}
const oldFormData = ref<any>({})
onMounted(() => {
  formId.value = route?.query?.id
  workFlowId.value = route?.query?.workFlowId
  if (workFlowId.value === '1') {
    // 延期缴纳罚款审批单
    component.value = penaltyDetail
  } else if (workFlowId.value === '2') {
    // 行政强制措施事项审批表
    component.value = CompulsoryAppDetail
  } else if (workFlowId.value === '3') {
    // 催告书审批表
    component.value = ReminderLetterDetail
  } else if (workFlowId.value === '4') {
    // 结案
    component.value = CaseClosedDetail
  } else if (workFlowId.value === '5') {
    // 立案审批表
    component.value = RegisterDetail
  } else if (workFlowId.value === '6') {
    // 事先告知审批表
    component.value = PriorNoticeDetail
  } else if (['7', '8'].includes(workFlowId.value)) {
    // 案件处理审批表
    component.value = CaseHandlingApprovalDetail
  } else if (workFlowId.value === '9') {
    // 法制审核意见书
    component.value = LegalReviewDetail
  } else if (workFlowId.value === '10') {
    // 撤案审批
    component.value = CaseWithdrawalDetail
  } else if (workFlowId.value === '11') {
    // 听证告知审批表
    component.value = HearingNoticeDetail
  } else if (workFlowId.value === '15') {
    // 听证申请审批表
    component.value = ApplicationDetail
  } else {
    component.value = 'div' // 默认组件，可以根据需要更改
    ElMessage.warning('表单待开发')
  }
  nextTick(async () => {
    componentRef.value?.getAnnotationList().then(res => {
      oldFormData.value = res || {}
      console.log('oldFormData', oldFormData.value)
    })
  })
})
</script>

<style lang="scss" scoped>
.page-content {
  display: flex;
  justify-content: flex-start;
  .form-container {
    width: calc(100% - 400px) !important;
  }
}
</style>
